/* 
 * Shuriken is the legal property of its developers. Please refer to the
 * COPYRIGHT file distributed with this
 * source distribution.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

using System;
using System.IO; 
using System.Collections.Generic;
using System.Text;
using System.Deployment; 

namespace Shuriken.Core.Utils
{
    /// <summary>
    /// AutoStart implementation class
    /// </summary>
    /// <remarks>
    /// ApplicationEnvironment class needs to be initialized otherwise this is not going to work.
    /// </remarks>
    public class AutoStart
    {
        /// <summary>
        /// Enables AutoStart
        /// </summary>
        /// <returns>true, if success</returns>
        public static bool EnableAutoStart()
        {
            return ChangeAutoStart(true);
        }

        /// <summary>
        /// Disables AutoStart
        /// </summary>
        /// <returns>true, if success</returns>
        public static bool DisableAutoStart()
        {
            return ChangeAutoStart(false);
        }

        /// <summary>
        /// Switches on-off AutoStart
        /// </summary>
        /// <param name="enable">enables Autostart, if true, disables otherwise</param>
        /// <returns>true, if success</returns>
        private static bool ChangeAutoStart(bool enable)
        {
            AutoStart astart = new AutoStart();

            if (astart.ClickOnceDeployment)
            {
                return enable ? astart.EnableClickOnceAutoStart() : astart.DisableClickOnceAutoStart();
            }
            else
            {
                return enable ? astart.EnableXCOPYAutoStart() : astart.DisableXCOPYAutoStart();
            }
        }
	
        /// <summary>
        /// ClickOnce deployed application
        /// </summary>
        /// <remarks>
        /// Tells if the currently runnign application is a ClickOnce deployed application 
        /// </remarks>
        private bool ClickOnceDeployment
        {
            get
            {
                return System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed;
            }
        }

        #region XCOPY 

        private string m_AutoStartRegistryKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
        
        /// <summary>
        /// Enables AutoStart for XCOPY deployment
        /// </summary>
        /// <returns>true, if success</returns>
        /// <remarks>
        /// Creating a value underneath the HKCU\Software\Microsoft\Windows\CurrentVersion\Run
        /// </remarks>
        private bool EnableXCOPYAutoStart()
        {
            // Create new registry key 
            string valueName = ApplicationEnvironment.ProductNameShort;
            string value = ApplicationEnvironment.ExecutablePath;
            bool writable = true;
            bool result = true;

            using (Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(m_AutoStartRegistryKey, writable))
            {
                if (regKey != null)
                {
                    regKey.SetValue(valueName, value, Microsoft.Win32.RegistryValueKind.String);
                }
                else
                {
                    result = false; 
                }
            }

            return result; 
        }

    
        /// <summary>
        /// Disables AutoStart for XCOPY deployment
        /// </summary>
        /// <returns>true, if success</returns>
        /// <remarks>
        /// Deleting the value underneath the HKCU\Software\Microsoft\Windows\CurrentVersion\Run
        /// </remarks>
        private bool DisableXCOPYAutoStart()
        {
            string valueName = ApplicationEnvironment.ProductNameShort;
            string value = ApplicationEnvironment.ExecutablePath;
            bool writable = true;
            bool result = true;

            using (Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(m_AutoStartRegistryKey, writable))
            {
                if (regKey != null)
                {
                    object o = regKey.GetValue(valueName);

                    if (o != null)
                    {
                        regKey.DeleteValue(valueName);
                    }
                }
                else
                {
                    result = false;
                }
            }

            return result;            
        }

        #endregion

        #region ClickOnce

        /// <summary>
        /// TESTONLY enables disables ClickOnce auto start 
        /// </summary>
        /// <param name="enable">if true enables auto start, disables otherwise</param>
        /// <returns>true, if successfull</returns>
        public static bool ChangeClickOnceAutoStart(bool enable)
        {
            AutoStart astart = new AutoStart();
            return enable ? astart.EnableClickOnceAutoStart() : astart.DisableClickOnceAutoStart();
        }

        /// <summary>
        /// Enables AutoStart for ClickOnce deployment
        /// </summary>
        /// <returns>true, if success</returns>
        private bool EnableClickOnceAutoStart()
        {
            string appref = ApplicationEnvironment.ProductNameShort + ".appref-ms";

            string startupFolderPath = Path.Combine(
                    System.Environment.GetFolderPath(Environment.SpecialFolder.Startup),
                    appref
                );
            
            string originalPath = Path.Combine(
                    Path.GetDirectoryName(ApplicationEnvironment.ExecutablePath),
                    appref
                );

            if (!File.Exists(originalPath))
            {
                return false;
            }

            File.Copy(originalPath, startupFolderPath);
                      
            return true; 
        }

        /// <summary>
        /// Disables AutoStart for XCOPY deployment
        /// </summary>
        /// <returns>true, if success</returns>
        private bool DisableClickOnceAutoStart()
        {
            string appref = ApplicationEnvironment.ProductNameShort + ".appref-ms";

            string startupFolderPath = Path.Combine(
                    System.Environment.GetFolderPath(Environment.SpecialFolder.Startup),
                    appref 
                );

            if (File.Exists(startupFolderPath))
            {
                File.Delete(startupFolderPath);
            }

            return true; 
        }

        #endregion
    }
}
